var fs=require("fs");

function load_fs_tree(basepath,path,arr,level)
{
	if (!arr) arr=[];
	if (!level) level=0;
	if (!path) path="";
	var dir=new fs.Directory(basepath+path);
	if (!dir.exists()) return arr;
	dir.listDirectories().forEach(function(d) {
		if (d.match(/^\./)) return;
		if (d=="_auto_admin" || d=="_models") return;
		arr.push({name:d,fullname:path+d+"/",level:level});
		load_fs_tree(basepath,path+d+"/",arr,level+1);
	});
	return arr;
}

exports.add=[
{
	_type:"controller",
	_config_details: {	
	},
	_config: {
		path:"adminpanel/",
		name:"AdminFileEditor",
		admin:1,
		role_code:"design"
	},
	
	_admin_nav: [
		{section:"settings",name:"File editor",mode:"index"}
	],

	/**
	 * Controller: AdminFileEditor.index 
	 *
	 * Returns:
	 *		HTML
	 */
	index: function(config) {
		return this.Cview();
	},

	/**
	 * Controller: AdminFileEditor.list
	 *
	 * Returns:
	 *		HTML
	 */
	list: function(config) {
		var data=(this.fields.system=="1")?this.system:this.site;
		var basepath;
		switch (this.fields.root) {
			case "controllers":
				basepath=data.paths.ssjs+"controllers/";
				break;
			case "models":
				basepath=data.paths.ssjs+"models/";
				break;
			case "sql":
				basepath=data.paths.sql;
				break;
			case "views":
				basepath=data.paths.views;
				break;
			case "html":
				basepath=data.paths.html;
				break;
			case "i18n":
				basepath=data.paths.i18n;
				break;
			case "config":
				if (this.fields.system=="1") basepath=system.cwd()+"config/";
				break;
			default:
				throw new Error("Unknown root type="+this.fields.root);
		}
		this.basepath=basepath;
		this.directories=load_fs_tree(basepath);
		return this.Cview();
	}
}];

